/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.dishes;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.Department;
import com.qinyeit.serviceapp.entity.DishesCategory;
import com.qinyeit.serviceapp.entity.enums.Industries;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.service.dishes.DishesCategoryService;
import com.qinyeit.serviceapp.service.dishes.DishesUnitService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.entity.DishesStore;
import com.qinyeit.serviceapp.service.dishes.DishesStoreService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * ClassName: DishesStoresController <br/>
 * Function: dishesStore [菜品库] <br/>
 * date: 2018-11-23 11:04:09 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/dishes/dishesStores")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_dishesStore:read",name ="菜品库",deleteAble = false)
public class DishesStoresController extends BaseManagementController{

	@Autowired
	private DishesStoreService dishesStoreService;
	@Autowired
	private DishesCategoryService dishesCategoryService;
	@Autowired
	private DishesUnitService dishesUnitService;

	private final String [] keys = {"id","name","creatorName","state","createAt","industry"};

    @RequiresPermissions("management_dishesStore:show")
    @PermissionInfo(code = "management_dishesStore:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){

        Page<Map<String,Object>> dishesStorePage = dishesStoreService.findAllForPage(searchable,CurrentAccountUtils.getAuthenticatedMerchantGroupID());

//        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
//        Page<DishesStore> dishesStorePage = dishesStoreService.findAll(searchable);
        QyMap map = QyMap.map("dishesStorePage", dishesStorePage);
        return ok("查询成功",map);
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("dishesStore",JSONUtils.include(new DishesStore(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_dishesStore:create")
    @PermissionInfo(code = "management_dishesStore:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid DishesStore dishesStore, BindingResult bindingResult){
        if(dishesStoreService.exists(SearchableUtils.buildExists(null, "name", dishesStore.getName()))){
             return fail("商品库名称已经存在");
        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        if(dishesStore.getIndustry()==null){
            return fail("请选择所属行业");
        }

        log.info("--------=====hangye  ========= :{}",dishesStore.getIndustry());
        dishesStore.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        dishesStore.setCreatorName(CurrentAccountUtils.getAuthenticatedEmployeeName());
        dishesStore = dishesStoreService.save(dishesStore);
        //创建菜品分类 名称为套餐，编号为00000
        dishesCategoryService.createDefault(dishesStore,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        //菜品单位 默认创建
        dishesUnitService.createDefault(dishesStore.getId(),CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute DishesStore dishesStore){
        return ok("查询成功", JSONUtils.include(dishesStore, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute DishesStore dishesStore){
        QyMap map=QyMap.NEW();
        map.setv("dishesStore",JSONUtils.include(dishesStore, keys));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_dishesStore:update")
    @PermissionInfo(code = "management_dishesStore:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid DishesStore dishesStore,BindingResult bindingResult){
//        if(dishesStoreService.exists(buildExists(null, "no", dishesStore.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }

        if(dishesStoreService.exists(SearchableUtils.buildExists(dishesStore.getId(), "name", dishesStore.getName()))){
            return fail("商品库名称已经存在");
        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        if(dishesStore.getIndustry()==null){
            return fail("请选择所属行业");
        }


        dishesStoreService.update(dishesStore);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_dishesStore:destory")
    @PermissionInfo(code = "management_dishesStore:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){

//        dishesStoreService.logicDelete(id);
        return ok("删除成功", null);
    }

    /**
     * 修改状态
     *
     * @param id
     * @return
     */
    @RequiresPermissions("management_dishesStore:updateState")
    @PermissionInfo(code = "management_dishesStore:updateState",name ="修改状态",deleteAble = false)
    @GetMapping("/updateState")
    public ResponseResult<String> updateState(Long id){
        DishesStore store = dishesStoreService.findById(id);
        if(store.getState()==State.NORMAL){
            store.setState(State.DISABLED);
        }else {
            store.setState(State.NORMAL);
        }
        dishesStoreService.update(store);
        return ok("操作成功", null);
    }

    /**
     * 获取菜品库下的菜品分类和菜品
     *
     * @param storeId
     * @return
     */
    @GetMapping("/getDishes")
    public ResponseResult<String> getDishes(Long storeId,boolean isNew,Long branchId){
        if (storeId==null){
            return fail("请选择菜品库",10001);
        }
        List<DishesCategory> categoryList = dishesStoreService.getDishesCategorys(storeId,isNew,branchId);
        return ok("查询成功", categoryList);
    }


    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            DishesStore dishesStore = dishesStoreService.findById(Long.valueOf(id));
            model.addAttribute(dishesStore);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        qyMap.setv("states",State.values());
        qyMap.setv("industryList", Industries.values());
    }

}